package com.suning.sncfc;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.Log;

import com.BV.LinearGradient.LinearGradientPackage;
import com.RNFetchBlob.RNFetchBlobPackage;
import com.alibaba.android.arouter.launcher.ARouter;
import com.android.volley.RequestQueue;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.beefe.picker.PickerViewPackage;
import com.bqs.risk.df.android.BqsDF;
import com.bqs.risk.df.android.BqsParams;
import com.csii.sncfc.BuildConfig;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;


import com.liulishuo.filedownloader.FileDownloader;

import com.imagepicker.ImagePickerPackage;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.L;
import com.psykar.cookiemanager.CookieManagerPackage;
import com.sjtu.baselib.util.SharePreferenceHelper;

import com.snc.appkernel.servicefactory.JJServiceFactory;
import com.snc.httptransportservice.info.SNCHttpTransportServiceInfoManager;
import com.snc.httptransportservice.network.SNCBaseRequest;
import com.snc.httptransportservice.urlconfig.SNCUrlConfigManager;

import com.sncfc.commlayer.UniqueIDUtil;
import com.suning.sncfc.app.Global;
import com.suning.sncfc.model.db.SNSQLiteOpenHelper;
import com.suning.sncfc.presenter.RnUpgradePresenter;
import com.suning.sncfc.reactview.ReactInputPackage;
import com.suning.sncfc.reactview.imageview.RnImagePackage;
import com.suning.sncfc.reactview.webview.RnWebviewPackage;
import com.suning.sncfc.ui.common.UserHandler;
import com.suning.sncfc.util.BaiduLocationHelper;
import com.sncfc.commlayer.CacheManager;

import com.suning.sncfc.util.CommonUtils;
import com.suning.sncfc.util.CrashHandler;
import com.suning.sncfc.util.DBUtil;
import com.suning.sncfc.util.DeviceInfoUtil;

import com.sncfc.commlayer.FileOperator;
import com.sncfc.commlayer.PreferenceUtil;
import com.sncfc.commlayer.TLog;


import com.suning.sncfc.util.JSONUtil;
import com.suning.sncfc.util.encrypt_old.MD5Util;

import com.suning.sncfc.util.http.HttpConfig;
import com.suning.sncfc.util.http.OkHttpStack;
import com.suning.sncfc.util.http.SNCFCVolley;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhuge.analysis.stat.ZhugeSDK;
import com.zhuge.reactnativezhuge.RNZhugeioPackage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Nullable;

import cn.jpush.android.api.JPushInterface;
import cn.tongdun.android.shell.FMAgent;
import cn.tongdun.android.shell.exception.FMException;
import im.shimo.react.preference.PreferencePackage;

public class MainApplication extends MultiDexApplication implements ReactApplication {

    /**
     * 上下文
     */
    private int mFinalCount;
    public static final int SESSION_TIMEOUT_MSGWHAT = 0x10001;
    private static Context mContext; /* 上下文 */
    private static MainApplication app = null; /* 本类实例对象 */
    public static String CHANNEL;
    private static Handler mainHandler;
    private String MI_PUSH_APP_ID = "2882303761517339439";
    private String MI_PUSH_APP_KEY = "5661733943439";
    public static String PUSH_APP_ID = "suningJr";
    private static String sysTime;
    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    new PreferencePackage(),
                    new PickerViewPackage(),
                    new CookieManagerPackage(),
                    new PlatformPluginManagerPackage(),
                    new LinearGradientPackage(),
                    new ReactInputPackage(),
                    new RnWebviewPackage(),
                    new RNFetchBlobPackage(),
                    new RNZhugeioPackage(),
                    new RnImagePackage(),
                    new ImagePickerPackage()
            );
        }

        @Nullable
        @Override
        protected String getJSBundleFile() {
            String version =UniqueIDUtil.getVersionName(getMyApplicationContext()) ;//3.2.0

            String hotfixVersion=PreferenceUtil.getString(PreferenceUtil.HOTFIXVERSION,getMyApplicationContext());//3.2.0.1
            String hotfixNewVersion=PreferenceUtil.getString(PreferenceUtil.HOTFIXVERSIONNEW,getMyApplicationContext());//3.2.0.2
            try {
                if (TextUtils.isEmpty(hotfixNewVersion)){//预更新版本为空
                    if (TextUtils.isEmpty(hotfixVersion)){//当前热更新版本为空
                        PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSION,"",getMyApplicationContext());
                        return super.getJSBundleFile();
                    }else {//当前热更新版本不为空
                      return getJSBundle(version,hotfixVersion);
                    }
                }else {////预更新版本不为空
                    return getJSBundle(version,hotfixNewVersion);
                }


            } catch (Exception e) {

                JSONObject object= new JSONObject();
                JSONUtil.put(object,"原因","原因 :"+e);
                ZhugeSDK.getInstance().track(MainApplication.getInstance(),"RN热更新-加载失败",object);
                e.printStackTrace();
                TLog._e("getJSBundleFile8",super.getJSBundleFile());
                PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSION,"",getMyApplicationContext());
                PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSIONNEW,"",getMyApplicationContext());
                return super.getJSBundleFile();
            }

        }
    };
    private RequestQueue reqQueue;

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this.getApplicationContext();
//        CustomTrust.getInstance().setEasyTrust(); //信任所有证书
        String processName = getProcessName(this, android.os.Process.myPid());
        if(getPackageName().equals(processName)){
            PreferenceUtil.putBoolean(PreferenceUtil.APPLOGKEY, true, MainApplication.getMyApplicationContext());
            TLog.init(getApplicationContext(), PreferenceUtil.getBoolean(PreferenceUtil.APPLOGKEY, !HttpConfig.PRODUCTION_MODE,MainApplication.getMyApplicationContext()),HttpConfig.PRODUCTION_MODE);
        }
        getCHANNEL();
        SoLoader.init(this, /* native exopackage */ false);
        // 捕获系统异常
        CrashHandler catchHandler = CrashHandler.getInstance();
        catchHandler.init(getApplicationContext());
        if (BuildConfig.DEBUG) { //如果在debug模式下
            // 打印日志,默认关闭
            ARouter.openLog();
            // 开启调试模式，默认关闭(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
            ARouter.openDebug();
            // 打印日志的时候打印线程堆栈
        }

        // 尽可能早，推荐在Application中初始化
        ARouter.init(this);

//
        //初始化科大讯飞
//        SpeechUtility.createUtility(this, SpeechConstant.APPID +"=597e930f");
        // 以下语句用于设置日志开关（默认开启），设置成false时关闭语音云SDK日志打印
        //   Setting.setShowLog(false);
        //初始化极光推送
        JPushInterface.setDebugMode(!HttpConfig.PRODUCTION_MODE);
        JPushInterface.init(this);
        //易付宝公共工具初始化
        //    EpaKitsApplication.setmContext(this);
        //同盾反欺诈SDK初始化
        try {
            if(HttpConfig.PRODUCTION_MODE){
                FMAgent.init(this, FMAgent.ENV_PRODUCTION);
            }else{
                FMAgent.init(this, FMAgent.ENV_SANDBOX);
            }
        } catch (FMException e) {
            e.printStackTrace();
        }

        initImageLoader(getApplicationContext());
        String path = "/data/data/com.csii.sncfc/databases/sncfc.db";
        File dbFile = new File(path);
        DBUtil.initDb(new SNSQLiteOpenHelper(this));


        //诸葛埋点
        if (HttpConfig.PRODUCTION_MODE) {
            ZhugeSDK.getInstance().setUploadURL("https://zhuge.sncfc.com.cn/APIPOOL/", "");
            ZhugeSDK.getInstance().init(getApplicationContext(), "cf8ce146d9f4481793e39bb67c0fbf44", CHANNEL);
        } else {
            ZhugeSDK.getInstance().setUploadURL("http://58.213.77.132/APIPOOL/", "");
            ZhugeSDK.getInstance().init(getApplicationContext(), "3c94ae5d5cd9427c8dc3e458af405a65", CHANNEL);
        }


        if (!HttpConfig.PRODUCTION_MODE) {
            ZhugeSDK.getInstance().openLog();
            ZhugeSDK.getInstance().setLogLevel(Log.INFO);
        }
        CrashReport.UserStrategy userStrategy = new CrashReport.UserStrategy(this);
        userStrategy.setAppChannel(CHANNEL);
        userStrategy.setAppReportDelay(20000);
        CrashReport.initCrashReport(getApplicationContext(), "c184716fbd", !HttpConfig.PRODUCTION_MODE, userStrategy);

        //初始化定位
        initLocation();
//        initPush();
        initBqsDFSDK();
        //初始化分享库
        // ShareSDK.initSDK(getApplicationContext());
        //  MobSDK.init(getApplicationContext(),"1c5246e99d328","f9a687620ab7fdcbab2205d26fbaac7f");
        //new GetFingerModel().getFinger();
        PreferenceUtil.putBoolean(PreferenceUtil.SHOWBILLNOTICE, true,MainApplication.getMyApplicationContext());
        initActivityRegister();
        initServiceFactory();
        ZhugeSDK.getInstance().setThirdPartyPushUserId(ZhugeSDK.PushChannel.JPUSH,JPushInterface.getRegistrationID(this));

        initDeviceInfo();

        FileDownloader.setup(this);
    }

    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    private void sendTimeMessage(String key, int time) {
        WritableMap writableMap = new WritableNativeMap();
        writableMap.putInt("backgroundTime", time);
        //说明从后台回到了前台
        if (Global.reactContext != null) {
            Global.reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                    .emit(key, writableMap);
        }
    }

    //初始化activity生命周斯监听
    private void initActivityRegister() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                mFinalCount++;
                //如果mFinalCount ==1，说明是从后台到前台
                if (mFinalCount == 1) {
                    Log.e("onActivity", mFinalCount + "Started");
                    String lastSaveTime = SharePreferenceHelper.getString(getMyApplicationContext(), "backgroundTime");
                    if (!TextUtils.isEmpty(lastSaveTime)) {//上次保存时间
                        try {
                            int gapTime = (int) (System.currentTimeMillis() - Long.parseLong(lastSaveTime));
                            sendTimeMessage("applicationWillEnterForeground", gapTime);
                        } catch (Exception e) {
                            sendTimeMessage("applicationWillEnterForeground", 0);
                        }
                    } else {
                        sendTimeMessage("applicationWillEnterForeground", 0);
                    }
                    SharePreferenceHelper.saveString(getMyApplicationContext(), "backgroundTime", System.currentTimeMillis() + "");
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                mFinalCount--;
                //如果mFinalCount ==0，说明是前台到后台
                if (mFinalCount == 0) {
                    Log.i("onActivity", mFinalCount + "Stopped");
                    //说明从前台回到了后台
                    String lastSaveTime = SharePreferenceHelper.getString(getMyApplicationContext(), "backgroundTime");
                    if (!TextUtils.isEmpty(lastSaveTime)) {//上次保存时间
                        try {
                            int gapTime = (int) (System.currentTimeMillis() - Long.parseLong(lastSaveTime));
                            sendTimeMessage("onDidEnterBackground", gapTime);
                        } catch (Exception e) {
                            sendTimeMessage("onDidEnterBackground", 0);
                        }
                    } else {
                        sendTimeMessage("onDidEnterBackground", 0);
                    }
                    SharePreferenceHelper.saveString(getMyApplicationContext(), "backgroundTime", System.currentTimeMillis() + "");
                    //用于删除
                    File rootDir = new File(Environment.getExternalStorageDirectory(), "sncfc");
                    File file = new File(rootDir.getAbsolutePath() + "/protocal.html");
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    private void initBqsDFSDK() {
        //1、配置初始化参数
        BqsParams params = new BqsParams();
        params.setPartnerId("sncfc");//商户编号
        params.setTestingEnv(!HttpConfig.PRODUCTION_MODE);//false是生产环境 true是测试环境
//        params.setGatherGps(true);
//        params.setGatherContact(true);
//        params.setGatherCallRecord(true);

        //2、执行初始化
        BqsDF.initialize(this, params);

        //3、提交tokenkey到贵公司服务器
//        HttpConfig.tokenkey = BqsDF.getTokenKey();

    }

    private void initImageLoader(Context context) {
        //缓存文件的目录
        File cacheDir = CacheManager.getCacheFile(context, "imageLoader/Cache");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .memoryCacheExtraOptions(480, 800) // max width, max height，即保存的每个缓存文件的最大长宽
                .threadPoolSize(3) //线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                // .diskCacheFileNameGenerator(new Md5FileNameGenerator()) //将保存的时候的URI名称用MD5 加密
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass
                // your own memory cache implementation/你可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值
                .diskCacheSize(50 * 1024 * 1024)  // 50 Mb sd卡(本地)缓存的最大值
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                // 由原先的discCache -> diskCache
                .diskCache(new UnlimitedDiskCache(cacheDir))//自定义缓存路径
                .imageDownloader(new BaseImageDownloader(context, 500, 30 * 1000)) //
                .build();
        //是否显示Log和错误信息
        L.writeLogs(true);
        L.writeDebugLogs(true);
        //全局初始化此配置
        ImageLoader.getInstance().init(config);

    }

    /**
     * 获取全局请求队列
     */
    public synchronized RequestQueue getReqQueue() {

        if (reqQueue == null) {
            reqQueue = SNCFCVolley.newRequestQueue(getApplicationContext(), new OkHttpStack());
        }
        return reqQueue;
    }

    /**
     * get application context
     *
     * @param
     * @return Context
     */
    public static Context getMyApplicationContext() {
        return mContext;
    }


    /**
     * initial Application instance
     *
     * @param
     * @return
     */
    public MainApplication() {
        app = this;
    }

    /**
     * get Application instance
     *
     * @param
     * @return MyApplication - Application instance
     */
    public static synchronized MainApplication getInstance() {
        if (app == null) {
            app = new MainApplication();
        }
        return app;
    }

    public String getCHANNEL() {
        if (CHANNEL == null) {
            try {
                ApplicationInfo appinfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
                CHANNEL = appinfo.metaData.getString("UMENG_CHANNEL");
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        if (CHANNEL == null) {
            CHANNEL = "sncfc";
        }
        TLog.d("MainApplication [getCHANNEL]  CHANNEL = " + CHANNEL);
        return CHANNEL;
    }

    public static Handler getMainHandler() {
        if (mainHandler == null) {
            mainHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case SESSION_TIMEOUT_MSGWHAT:
                            TLog.d("SESSION_TIMEOUT_MSGWHAT");
                            if (UserHandler.isLoginStatus()) {
                                UserHandler.sessionTimeoutFlag = true;
                            }
                            break;
                    }

                }
            };
        }
        return mainHandler;
    }

    public String getSysTime() {
        return sysTime;
    }

    public void setSysTime(String sysTime) {
        this.sysTime = sysTime;
    }

    private void initLocation() {
        final BaiduLocationHelper locationHelper = BaiduLocationHelper.getBaiduLocationHelper();
        locationHelper.LocationInit(MainApplication.getInstance());
        locationHelper.startLocation(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (bdLocation == null) {
//                    locationHelper.startLocation(this);
                    return;
                }
                if(TextUtils.isEmpty(bdLocation.getCity())){
                    return;
                }

                double latitude = bdLocation.getLatitude();
                double longitude = bdLocation.getLongitude();
                String city = bdLocation.getCity();
                String cityCode = bdLocation.getCityCode();
                String district = bdLocation.getDistrict();
                TLog.d("当前位置信息: " + "城市 " + city + "经度 " + longitude + " 维度 " + latitude + "cityCode " + cityCode + "   district = " + district + "   LocType = " + bdLocation.getLocType());
//                PreferenceUtil.putString(Global.LOCA_LATITUDE, latitude + "");
//                PreferenceUtil.putString(Global.LOCA_LONGITUDE, longitude + "");
//                if (!TextUtils.isEmpty(city)) {
                Global.CITY = city;
                Global.LOCA_LATITUDE = latitude + "";
                Global.LOCA_LONGITUDE = longitude + "";
                Global.DEVICEINFO_MAP.put("客户LBS 经度", Global.LOCA_LONGITUDE);
                Global.DEVICEINFO_MAP.put("客户LBS 纬度", Global.LOCA_LATITUDE);
                Global.DEVICEINFO_MAP.put("LBS经纬度地址", bdLocation.getAddrStr());
//                    PreferenceUtil.putString(Global.CITY, city);
////                }
                locationHelper.stopLocation();
            }
        });
    }

    public static final String LOGIN_SUCCESS_ACTION = "k_SNC_LOGIN_SUCCESS";
    public static final String LOGOUT_SUCCESS_ACTION = "k_SNC_LOGOUT_SUCCESS";

    /**
     * 初始化Service 配置
     */
    private void initServiceFactory() {

        List<String> loginSuccessArray = new ArrayList<>();
        loginSuccessArray.add(LOGIN_SUCCESS_ACTION);
        List<String> logoutSuccessArray = new ArrayList<>();
        logoutSuccessArray.add(LOGOUT_SUCCESS_ACTION);
        logoutSuccessArray.add(SNCBaseRequest.FORCELOGOUT);

        JJServiceFactory.getInstance().setLoginSuccessNotificationActionArray(loginSuccessArray);
        JJServiceFactory.getInstance().setLogoutNotificationActionArray(logoutSuccessArray);
        JJServiceFactory.getInstance().setContext(getApplicationContext());

        SNCHttpTransportServiceInfoManager.getInstance().setAppVersion(UniqueIDUtil.getVersionName(this));
        SNCHttpTransportServiceInfoManager.getInstance().setTerminalType(Global.TERMINALTYPE);

        String jsonString = FileOperator.readAssetFile(getApplicationContext(), "SNCUrlConfig.json");
        try {
            JSONObject urlConfigObject = new JSONObject(jsonString);
            SNCUrlConfigManager.getInstance().addUrlConfig(urlConfigObject);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        //设置 服务器环境
        SNCUrlConfigManager.getInstance().setEnvironment("Product");
    }


    private void initDeviceInfo(){
        BatteryReceiver batteryReceiver = new BatteryReceiver();
        registerReceiver(batteryReceiver,intentFilter);
        new Thread(){
            @Override
            public void run() {
                //手机端ip地址
                Global.DEVICEINFO_MAP.put("手机客户端IP",DeviceInfoUtil.getHostIp());
                //获取手机外网IP地址及省市
                DeviceInfoUtil.NetInfo netInfo = DeviceInfoUtil.getNetIpInfo();
                if(netInfo != null){
                    Global.DEVICEINFO_MAP.put("IP所属省份",netInfo.region);
                    Global.DEVICEINFO_MAP.put("IP所属城市",netInfo.city);
                    Global.DEVICEINFO_MAP.put("手机外网IP",netInfo.ip);
                }
                Global.DEVICEINFO_MAP.put("是否root/越狱", CommonUtils.checkRootWhichSU()+"");
                Global.DEVICEINFO_MAP.put("设备所有者名称", DeviceInfoUtil.getDeviceName());
                Global.DEVICEINFO_MAP.put("MAC地址", UniqueIDUtil.getMacIp(mContext));
                Global.DEVICEINFO_MAP.put("操作系统", "Android");
                Global.DEVICEINFO_MAP.put("操作系统版本号", UniqueIDUtil.getOSVersion());
                Global.DEVICEINFO_MAP.put("设备号", DeviceInfoUtil.getDeviceId(mContext));
                Global.DEVICEINFO_MAP.put("端类型", "Android");
                Global.DEVICEINFO_MAP.put("分辨率高", DeviceInfoUtil.getScreenHeight(mContext)+"");
                Global.DEVICEINFO_MAP.put("分辨率宽", DeviceInfoUtil.getScreenWidth(mContext)+"");
                Global.DEVICEINFO_MAP.put("WIFI MAC地址", DeviceInfoUtil.getMacAddress(mContext));
                Global.DEVICEINFO_MAP.put("WIFI名称", DeviceInfoUtil.getWifiSSID(mContext));
                Global.DEVICEINFO_MAP.put("磁盘容量", DeviceInfoUtil.getTotalInternalMemorySize()+"M");
                Global.DEVICEINFO_MAP.put("可用容量", DeviceInfoUtil.getAvailableInternalMemorySize()+"M");
            }
        }.start();
    }

    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    class BatteryReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            //判断它是否是为电量变化的Broadcast Action
            if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())){
                //获取当前电量
                int level = intent.getIntExtra("level", 0);
                //电量的总刻度
                int scale = intent.getIntExtra("scale", 100);
                //把它转成百分比
               // Global.BATTERY_LEVEL = ((level*100)/scale)+"%";
            }
        }

    }

    /**
     * 判断文件存在并且MD5值相等
     * @param hotfixVersion
     * @return
     */
    private boolean fileExistAndMd5Equals(String hotfixVersion){
        String filePath = Global.HOTFIXPATH + "/snc_rn_android_"+hotfixVersion+"/"+Global.JS_BUNDLE_LOCAL_FILE;
        File file = new File(filePath);
      boolean fileExists= file.exists();
      String filePutMd5 =  PreferenceUtil.getString(hotfixVersion,getMyApplicationContext());
        if (fileExists){
            String fileMd5 =  MD5Util.getFileMD5(file);
            if (filePutMd5.equals(fileMd5)){
                return true;
            }else {
                JSONObject object= new JSONObject();
                JSONUtil.put(object,"原因","原因 :MD5不一致");
                ZhugeSDK.getInstance().track(MainApplication.getInstance(),"RN热更新-加载失败",object);
                return false;
            }
        }else {
            JSONObject object= new JSONObject();
            JSONUtil.put(object,"原因","原因 :文件不存在");
            ZhugeSDK.getInstance().track(MainApplication.getInstance(),"RN热更新-加载失败",object);
            return false;
        }


    }

    /**
     * 判断version 与热更新版本大小关系
     * @param version
     * @param hotfixVersion
     * @return
     * @throws Exception
     */
    private String getJSBundle(String version,String hotfixVersion) throws Exception {
        if (CommonUtils.compareVersion(version,hotfixVersion)>0){//判断version,hotfixVersion大小
            TLog._e("getJSBundleFile5","null");
            PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSION,"",getMyApplicationContext());
            CommonUtils.deleteFileDirectory(new File(Global.HOTFIXPATH));
            return null;
        }else {
            if (fileExistAndMd5Equals(hotfixVersion)){//hotfixVersion是否存在，获取bundle路径
                JSONObject object= new JSONObject();
                JSONUtil.put(object,"版本号","版本号 :"+hotfixVersion);
                ZhugeSDK.getInstance().track(MainApplication.getInstance(),"RN热更新-加载成功",object);
                PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSION,hotfixVersion,getMyApplicationContext());
                return Global.HOTFIXPATH+"/snc_rn_android_"+hotfixVersion+"/"+Global.JS_BUNDLE_LOCAL_FILE;
            }else {
                PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSION,"",getMyApplicationContext());
                return null;
            }

        }
    }
}
